'use strict';

const ulid = require('../public/ulid');

const Service = require('egg').Service;

class ResourceService extends Service {
  async list(params) {
    const tid = params.tid;
    return await this.ctx.model.Resource.findAndCountAll({
      where: { tid },
      order: [[ 'createdAt', 'ASC' ]],
      offset: parseInt((params.page - 1) * params.limit),
      limit: parseInt(params.limit),
    });
  }
  async listAll(tid) {
    return await this.ctx.model.Resource.findAll({
      where: { tid },
      order: [[ 'createdAt', 'ASC' ]],
    });
  }
  async create(params) {
    const result = {
      msg: '',
    };
    const tid = params.tid;
    try {
      await this.ctx.model.Resource.create({
        id: ulid.ulid(),
        ResourceType: params.resourceType,
        URL: params.URL,
        Route: params.Route,
        parentid: params.Parentid,
        Name: params.Name,
        tid,
      });
      result.msg = 'create successful';
      return result;
    } catch (error) {
      result.msg = 'create fail';
      return result;
    }
  }

  async delete(params) {
    const result = {
      msg: '',
    };
    try {
      await this.ctx.model.Resource.destroy({ where: { id: params.id } });
      result.msg = 'delete successful';
      return result;
    } catch (error) {
      result.msg = 'delete fail';
      return result;
    }
  }
  async edit(params) {
    const result = {
      msg: '',
    };
    try {
      await this.ctx.model.Resource.update({
        ResourceType: params.resourceType,
        URL: params.URL,
        Route: params.route,
        parentid: params.parentid,
      }, {
        where: { id: params.id },
      });
      result.msg = 'edit successful';
      return result;
    } catch (error) {
      result.msg = 'edit successful';
      return result;
    }
  }
}

module.exports = ResourceService;
